import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

class WindowBinding {
  static double onePixel = 1.0 / window.devicePixelRatio;
  static Future<void> initialized() async {
    if (isDesktop()) {
      double devicePixelRatio = window.devicePixelRatio;
      Size defaultSize = Size(1024 / devicePixelRatio, 576 / devicePixelRatio);
      Size minSize = Size(768 / devicePixelRatio, 432 / devicePixelRatio);
      await windowManager.ensureInitialized();
      await windowManager.waitUntilReadyToShow(
          WindowOptions(
              size: defaultSize,
              minimumSize: minSize,
              center: true,
              skipTaskbar: false,
              titleBarStyle: TitleBarStyle.hidden,
              windowButtonVisibility: false), () async {
        await windowManager.center();
        await windowManager.setAsFrameless();
        await windowManager.setHasShadow(true);
        await windowManager.show();
        await windowManager.focus();
      });
    }
  }

  // 是否桌面
  static isDesktop() {
    return Platform.isWindows || Platform.isMacOS || Platform.isLinux;
  }
}

class DragToMoveArea extends StatelessWidget {
  final Widget child;

  const DragToMoveArea({
    super.key,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid || Platform.isIOS) return child;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onPanStart: (details) {
        windowManager.startDragging();
      },
      child: child,
    );
  }
}

class DragToMoveWrapper extends StatelessWidget {
  final Widget child;
  final bool canDouble;

  const DragToMoveWrapper(
      {super.key, required this.child, this.canDouble = false});

  @override
  Widget build(BuildContext context) {
    bool isDesk = Platform.isMacOS || Platform.isWindows || Platform.isLinux;
    if (!isDesk) return child;
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onDoubleTap: !canDouble
          ? null
          : () async {
              bool isMax = await windowManager.isMaximized();
              if (isMax) {
                windowManager.unmaximize();
              } else {
                windowManager.maximize();
              }
            },
      onPanStart: (details) {
        windowManager.startDragging();
      },
      child: child,
    );
  }
}

class WindowButtons extends StatefulWidget {
  final List<Widget>? actions;
  final bool disabledMaximize;
  final double radius;
  const WindowButtons(
      {super.key,
      this.actions,
      this.disabledMaximize = false,
      this.radius = 4});

  @override
  State<WindowButtons> createState() => _WindowButtonsState();
}

class _WindowButtonsState extends State<WindowButtons> {
  @override
  Widget build(BuildContext context) {
    Brightness brightness = Theme.of(context).brightness;
    return Align(
      alignment: Alignment.topRight,
      child: Wrap(
        spacing: 5,
        children: [
          if (widget.actions != null) ...widget.actions!,
          ClipRRect(
            borderRadius: BorderRadius.circular(widget.radius),
            child: SizedBox(
              width: 30,
              height: 30,
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                child: WindowCaptionButton.minimize(
                  brightness: brightness,
                  onPressed: () async {
                    bool isMinimized = await windowManager.isMinimized();
                    if (isMinimized) {
                      windowManager.restore();
                    } else {
                      windowManager.minimize();
                    }
                  },
                ),
              ),
            ),
          ),
          widget.disabledMaximize
              ? Container()
              : ClipRRect(
                  borderRadius: BorderRadius.circular(widget.radius),
                  child: SizedBox(
                    width: 30,
                    height: 30,
                    child: MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: FutureBuilder<bool>(
                        future: windowManager.isMaximized(),
                        builder: (BuildContext context,
                            AsyncSnapshot<bool> snapshot) {
                          if (snapshot.data == true) {
                            return WindowCaptionButton.unmaximize(
                              brightness: brightness,
                              onPressed: () async {
                                await windowManager.unmaximize();
                                setState(() {});
                              },
                            );
                          }
                          return WindowCaptionButton.maximize(
                            brightness: brightness,
                            onPressed: () async {
                              await windowManager.maximize();
                              setState(() {});
                            },
                          );
                        },
                      ),
                    ),
                  ),
                ),
          ClipRRect(
            borderRadius: BorderRadius.circular(widget.radius),
            child: SizedBox(
              height: 30,
              width: 30,
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                child: WindowCaptionButton.close(
                  brightness: brightness,
                  onPressed: () {
                    windowManager.close();
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
